from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtSql import *
from math import *
import Ui_unitEdit
import master.utility as utility
import tenantSrc

class UnitEdit(QDialog, Ui_unitEdit.Ui_unitEditDlg):
  StyleSheet = """
QLineEdit[mandatory="true"] {
    background-color: rgb(255, 255, 127);
    color: darkblue;
}
"""
  def __init__(self, dbConn, tipe, dataGlob, parent=None):
        super(UnitEdit, self).__init__(parent)
        self.setupUi(self)
        self.db = dbConn
        self.tipe = tipe
        self.initFinished = False
        self.dataGlob = dataGlob
        self.util = utility.Utility(self.db)
        
        self.mastModel = QSqlTableModel(self)
        self.mastModel.setTable("base_unit")
        self.mastModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        
        self.billModel = QSqlRelationalTableModel(self)
        self.billModel.setTable("base_unit_det_bill")
        self.billModel.setRelation(3, QSqlRelation("master_tarif_detail", "kode_tarif", "kode_tarif"))
        self.billModel.setRelation(5, QSqlRelation("master_pemilik_penyewa", "kode_pemilik_penyewa", "nama_pemilik_penyewa"))
        self.billModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.billModel.setFilter("kode_unit = '"+self.tipe+"'")
        self.billModel.setHeaderData(2, Qt.Horizontal, QVariant("Bill Type"))
        self.billModel.setHeaderData(3, Qt.Horizontal, QVariant("Tarif ID"))
        self.billModel.setHeaderData(4, Qt.Horizontal, QVariant("Meter No"))
        self.billModel.setHeaderData(5, Qt.Horizontal, QVariant("Bill To"))
        self.billModel.setHeaderData(6, Qt.Horizontal, QVariant("Billed"))
        self.billModel.select()
        
        self.billing_tbv.setModel(self.billModel)
        self.billing_tbv.setItemDelegate(DetailDelegate(self))
        self.billing_tbv.setSelectionMode(QTableView.SingleSelection)
        self.billing_tbv.setSelectionBehavior(QTableView.SelectRows)
        self.billing_tbv.setColumnHidden(0, True)
        self.billing_tbv.setColumnHidden(1, True)
        self.billing_tbv.setColumnWidth(5, 200)
        
        self.urutBill= 0
        if self.tipe != "add":
            query = QSqlQuery(self.db)
            query.exec_("select max(urut) from base_unit_det_bill where kode_unit = '"+self.tipe+"'")
            while query.next():
                self.urutBill = query.value(0).toInt()[0]        
        
        self.joinModel = QSqlTableModel(self)
        self.joinModel.setTable("base_unit_detail")
        self.joinModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.joinModel.setFilter("kode_unit = '"+self.tipe+"'")
        self.joinModel.setHeaderData(2, Qt.Horizontal, QVariant("Unit Join"))
        self.joinModel.select()
        
        self.joinUnit_tbv.setModel(self.joinModel)
        self.joinUnit_tbv.setSelectionMode(QTableView.SingleSelection)
        self.joinUnit_tbv.setSelectionBehavior(QTableView.SelectRows)
        self.joinUnit_tbv.setColumnHidden(0, True)
        self.joinUnit_tbv.setColumnHidden(1, True)
        self.joinUnit_tbv.setColumnHidden(3, True)
        self.joinUnit_tbv.setColumnWidth(2, 200)
        self.joinEdited = False
        
        self.urutJoin= 0
        if self.tipe != "add":
            query = QSqlQuery(self.db)
            query.exec_("select max(no_urut) from base_unit_detail where kode_unit = '"+self.tipe+"'")
            while query.next():
                self.urutJoin = query.value(0).toInt()[0]        
        
        self.areaModel = QSqlTableModel(self)
        self.areaModel.setTable("base_unit_det_unit")
        self.areaModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        self.areaModel.setFilter("kode_unit = '"+self.tipe+"'")
        self.areaModel.setHeaderData(2, Qt.Horizontal, QVariant("Floor"))
        self.areaModel.setHeaderData(3, Qt.Horizontal, QVariant("Sqrm"))
        self.areaModel.setHeaderData(4, Qt.Horizontal, QVariant("SC Tarif"))
        self.areaModel.setHeaderData(5, Qt.Horizontal, QVariant("SF Tarif"))
        self.areaModel.select()
        
        self.area_tbv.setModel(self.areaModel)
        self.area_tbv.setSelectionMode(QTableView.SingleSelection)
        self.area_tbv.setSelectionBehavior(QTableView.SelectRows)
        self.area_tbv.setColumnHidden(0, True)
        self.area_tbv.setColumnHidden(1, True)
        
        self.urutArea= 0
        if self.tipe != "add":
            query = QSqlQuery(self.db)
            query.exec_("select max(urut) from base_unit_det_unit where kode_unit = '"+self.tipe+"'")
            while query.next():
                self.urutArea = query.value(0).toInt()[0]        
        
        self.tipeModel = QSqlTableModel(self)
        self.tipeModel.setTable("master_type_unit")
        self.tipeModel.select()
        self.tipe_cmb.setModel(self.tipeModel)
        self.tipe_cmb.setModelColumn(2)
        self.tipe_cmb.setCurrentIndex(0)
        
        self.bisnisModel = QSqlTableModel(self)
        self.bisnisModel.setTable("master_bisnis_unit")
        self.bisnisModel.select()
        self.cat_cmb.setModel(self.bisnisModel)
        self.cat_cmb.setModelColumn(1)
        self.cat_cmb.setCurrentIndex(0)
        
#        self.idModel = QSqlTableModel(self)
#        self.idModel.setTable("master_nodok")
#        self.idModel.setEditStrategy(QSqlTableModel.OnManualSubmit)
        
        self.urut = 0
        if self.tipe != "add":
            query = QSqlQuery(self.db)
            query.exec_("select max(urut) from base_unit_det_bill where kode_unit = '"+self.tipe+"'")
            while query.next():
                self.urut = query.value(0).toInt()[0]
                
        self.dataJoin = {"N":"No Join", "G":"Group Join", "J":"Join To Other"}
        self.initData()
        
        self.lineedits = (self.unit_le, self.name_le,  self.sqrm_le)
        for lineEdit in self.lineedits:
            lineEdit.setProperty("mandatory", QVariant(True))
        self.setStyleSheet(UnitEdit.StyleSheet)

  @pyqtSignature("")
  def on_save_pb_clicked(self):
      if self.id_le.text().isEmpty():
          parm = "new"
      else:
          parm = "update"
      if self.simpan(parm):
          self.close()
      else:
          QMessageBox.warning(self, "Unit","Can't add new / update data.")
          
  @pyqtSignature("")
  def on_cancel_pb_clicked(self):
      self.close()

  @pyqtSignature("")
  def on_findOwner_pb_clicked(self):
      form = tenantSrc.TenantSrc(self.db, self)
      if form.exec_():
          id = form.getID()
          self.idO_le.setText(id)
          query = QSqlQuery(self.db)
          query.exec_("select kode_pemilik_penyewa, nama_pemilik_penyewa, concat(alamat_pemilik_penyewa,' ', kota_pemilik_penyewa) as alm, no_telp, no_ponsel, no_fax, kode_tt, nama_pt, no_telp_pt, concat(alamat_pt,' ',kota_pt), email from master_pemilik_penyewa where kode_pemilik_penyewa = '"+id+"'")
          query.next()
          self.nameO_le.setText(unicode(query.value(1).toString()))
          self.addrO_le.setText(unicode(query.value(2).toString()))
          self.phoneO_le.setText(unicode(query.value(3).toString()))
          self.hpO_le.setText(unicode(query.value(4).toString()))
          self.faxO_le.setText(unicode(query.value(5).toString()))
          self.typeO_le.setText(unicode(query.value(6).toString()))
          self.compO_le.setText(unicode(query.value(7).toString()))
          self.phone2O_le.setText(unicode(query.value(8).toString()))
          self.addr2O_le.setText(unicode(query.value(9).toString()))

  @pyqtSignature("")
  def on_findTenant_pb_clicked(self):
      form = tenantSrc.TenantSrc(self.db, self)
      if form.exec_():
          id = form.getID()
          self.idT_le.setText(id)
          query = QSqlQuery(self.db)
          query.exec_("select kode_pemilik_penyewa, nama_pemilik_penyewa, concat(alamat_pemilik_penyewa,' ', kota_pemilik_penyewa) as alm, no_telp, no_ponsel, no_fax, kode_tt, nama_pt, no_telp_pt, concat(alamat_pt,' ',kota_pt), email from master_pemilik_penyewa where kode_pemilik_penyewa = '"+id+"'")
          query.next()
          self.nameT_le.setText(unicode(query.value(1).toString()))
          self.addrT_le.setText(unicode(query.value(2).toString()))
          self.phoneT_le.setText(unicode(query.value(3).toString()))
          self.hpT_le.setText(unicode(query.value(4).toString()))
          self.faxT_le.setText(unicode(query.value(5).toString()))
          self.typeT_le.setText(unicode(query.value(6).toString()))
          self.compT_le.setText(unicode(query.value(7).toString()))
          self.phone2T_le.setText(unicode(query.value(8).toString()))
          self.addr2T_le.setText(unicode(query.value(9).toString()))
          
  @pyqtSignature("")
  def on_addJoin_pb_clicked(self):
      self.urutJoin += 1
      if self.id_le.text() == "":
          if not self.simpan("new"):
              QMessageBox.warning(self, "Unit","Can't add new data.")
              return
      self.joinModel.setFilter("kode_unit = '"+self.id_le.text()+"'")
      self.joinModel.select()
      QSqlDatabase.database().transaction()
      row = self.joinModel.rowCount()    
      self.joinModel.insertRow(row)
      self.joinModel.setData(self.joinModel.index(row, 0), QVariant(self.id_le.text()))
      self.joinModel.setData(self.joinModel.index(row, 1), QVariant(self.urutJoin))
      QSqlDatabase.database().commit()
      index = self.joinModel.index(row, 2)
      self.joinUnit_tbv.setCurrentIndex(index)
      self.joinUnit_tbv.edit(index)
      self.joinEdited = True
          
  @pyqtSignature("")
  def on_delJoin_pb_clicked(self):
      index = self.joinUnit_tbv.currentIndex()
      if not index.isValid():
          return
      self.joinModel.removeRow(index.row())
      self.joinModel.submitAll()
          
  @pyqtSignature("")
  def on_addArea_pb_clicked(self):
      self.urutArea += 1
      if self.id_le.text() == "":
          if not self.simpan("new"):
              QMessageBox.warning(self, "Unit","Can't add new data.")
              return
      self.areaModel.setFilter("kode_unit = '"+self.id_le.text()+"'")
      self.areaModel.select()
      QSqlDatabase.database().transaction()
      row = self.areaModel.rowCount()    
      self.areaModel.insertRow(row)
      self.areaModel.setData(self.areaModel.index(row, 0), QVariant(self.id_le.text()))
      self.areaModel.setData(self.areaModel.index(row, 1), QVariant(self.urutJoin))
#      self.areaModel.submitAll()
      QSqlDatabase.database().commit()
      index = self.areaModel.index(row, 2)
      self.area_tbv.setCurrentIndex(index)
      self.area_tbv.edit(index)
          
  @pyqtSignature("")
  def on_delArea_pb_clicked(self):
      index = self.area_tbv.currentIndex()
      if not index.isValid():
          return
      self.areaModel.removeRow(index.row())
      self.areaModel.submitAll()
          
  @pyqtSignature("")
  def on_addBill_pb_clicked(self):
      self.urutBill += 1
      if self.id_le.text() == "":
          if not self.simpan("new"):
              QMessageBox.warning(self, "Unit","Can't add new data.")
              return
          self.billModel.setFilter("kode_unit = '"+self.id_le.text()+"'")
          self.billModel.select()
      QSqlDatabase.database().transaction()
      row = self.billModel.rowCount()      
      self.billModel.insertRow(row)
      self.billModel.setData(self.billModel.index(row, 0), QVariant(self.id_le.text()))
      self.billModel.setData(self.billModel.index(row, 1), QVariant(self.urutBill))
#      self.detModel.submitAll()
      QSqlDatabase.database().commit()
      index = self.billModel.index(row, 2)
      self.billing_tbv.setCurrentIndex(index)
      self.billing_tbv.edit(index)

  @pyqtSignature("")
  def on_delBill_pb_clicked(self):
      index = self.billing_tbv.currentIndex()
      if not index.isValid():
          return
      self.billModel.removeRow(index.row())
      self.billModel.submitAll()
      
  @pyqtSignature("")
  def on_changeBill_pb_clicked(self):
      jum_brs = self.billModel.rowCount()
      for i in range(jum_brs):
          tipe = self.billModel.record(i).value(2).toString()
          if tipe == "SC" or tipe == "SF":
              self.setTagih("sfsc",  i)
          else:
              self.setTagih("util",  i)
      
  @pyqtSignature("")
  def on_elc_cb_clicked(self):
      cek = "Y" if self.elc_cb.checkState() == Qt.Checked else "N"
      self.detail_bill("ELC", cek)
      
  @pyqtSignature("")
  def on_wtr_cb_clicked(self):
      cek = "Y" if self.wtr_cb.checkState() == Qt.Checked else "N"
      self.detail_bill("WTR", cek)
      
  @pyqtSignature("")
  def on_gas_cb_clicked(self):
      cek = "Y" if self.gas_cb.checkState() == Qt.Checked else "N"
      self.detail_bill("GAS", cek)
      
  @pyqtSignature("")
  def on_sc_cb_clicked(self):
      cek = "Y" if self.sc_cb.checkState() == Qt.Checked else "N"
      self.detail_bill("SC", cek)
      
  @pyqtSignature("")
  def on_sf_cb_clicked(self):
      cek = "Y" if self.sf_cb.checkState() == Qt.Checked else "N"
      self.detail_bill("SF", cek)
      
  @pyqtSignature("")
  def on_utilOwner_rb_clicked(self):
      if self.utilOwner_rb.isChecked():
          self.setTagihAll("util",  self.idO_le.text())
      
  @pyqtSignature("")
  def on_utilTenant_rb_clicked(self):
      if self.utilTenant_rb.isChecked():
          self.setTagihAll("util",  self.idT_le.text())
      
  @pyqtSignature("")
  def on_utilDev_rb_clicked(self):
      if self.utilDev_rb.isChecked():
          self.setTagihAll("util",  "CBP100001")
      
  @pyqtSignature("")
  def on_scOwner_rb_clicked(self):
      if self.scOwner_rb.isChecked():
          self.setTagihAll("sfsc",  self.idO_le.text())
      
  @pyqtSignature("")
  def on_scTenant_rb_clicked(self):
      if self.scTenant_rb.isChecked():
          self.setTagihAll("sfsc",  self.idT_le.text())
      
  @pyqtSignature("")
  def on_scDev_rb_clicked(self):
      if self.scDev_rb.isChecked():
          self.setTagihAll("sfsc",  "CBP100001")
      
  @pyqtSignature("int")
  def on_statJoin_cmb_currentIndexChanged(self, idx):
      if idx == 1:
          self.addJoin_pb.setEnabled(True)
          self.delJoin_pb.setEnabled(True)
      else:
          self.addJoin_pb.setEnabled(False)
          self.delJoin_pb.setEnabled(False)
      
  @pyqtSignature("int")
  def on_tipe_cmb_currentIndexChanged(self, idx):
      if self.initFinished:
          if self.billModel.rowCount() > 0:
              self.tab_det.setCurrentIndex(4)
              query = QSqlQuery()
              brs = self.billModel.match(self.billModel.index(0, 2), 2, QVariant("SC"),1, Qt.MatchWrap )
              if len(brs) > 0:
                  namaTipeUnit = "SC "+self.tipeModel.data(self.tipeModel.index(idx, 1)).toString()
                  query.exec_("select kode_tarif from master_tarif_detail where status = 'A' and kode_tarif like '"+namaTipeUnit+"%'")
                  while query.next():
                      self.billModel.setData(self.billModel.index(brs[0].row(), 3), query.value(0))
              brs = self.billModel.match(self.billModel.index(0, 2), 2, QVariant("SF"),1, Qt.MatchWrap )
              if len(brs) > 0:
                  namaTipeUnit = "SF "+self.tipeModel.data(self.tipeModel.index(idx, 1)).toString()
                  query.exec_("select kode_tarif from master_tarif_detail where status = 'A' and kode_tarif like '"+namaTipeUnit+"%'")
                  while query.next():
                      self.billModel.setData(self.billModel.index(brs[0].row(), 3), query.value(0))
                      
          if self.tipe_cmb.currentText().left(3) != "EXT" and self.areaModel.rowCount() > 0:
              self.tab_det.setCurrentIndex(3)
              QMessageBox.warning(self, "Unit Edit", "Please check detail area")
      
  def simpan(self,  parm):
      if not self.validasi():
          return
      if parm == "new":
          idBaru = self.idBaru()
          self.id_le.setText(idBaru)
          self.tipe = idBaru
      else:
          self.billModel.submitAll()
          self.joinModel.submitAll()
          self.areaModel.submitAll()
          
      self.mastModel.setFilter("kode_unit = '"+self.tipe+"'")
      self.mastModel.select()     
      QSqlDatabase.database().transaction()
      if parm == "new":
          if not self.mastModel.insertRow(0):
              return
          self.mastModel.setData(self.mastModel.index(0, 19), QVariant(self.id_le.text()))
          
      self.mastModel.setData(self.mastModel.index(0, 0), QVariant(self.unit_le.text()))
      
      brs = self.tipe_cmb.currentIndex()
      tipeUnit = self.tipeModel.data(self.tipeModel.index(brs, 0)).toString()
      self.mastModel.setData(self.mastModel.index(0, 1), QVariant(tipeUnit))
      
      self.mastModel.setData(self.mastModel.index(0, 2), QVariant(self.name_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 3), QVariant(self.sqrm_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 4), QVariant(self.ho_de.date()))
      self.mastModel.setData(self.mastModel.index(0, 5), QVariant(self.rentStart_de.date()))
      self.mastModel.setData(self.mastModel.index(0, 6), QVariant(self.rentEnd_de.date()))
      
      brs = self.cat_cmb.currentIndex()
      bisnisUnit = self.bisnisModel.data(self.bisnisModel.index(brs, 0)).toString()
      self.mastModel.setData(self.mastModel.index(0, 7), QVariant(bisnisUnit))
      
      self.mastModel.setData(self.mastModel.index(0, 8), QVariant(self.phone_le.text()))
      
      bukaStat = "1" if self.open_cb.checkState() == Qt.Checked else "2"
      self.mastModel.setData(self.mastModel.index(0, 9), QVariant(bukaStat))
      
      self.mastModel.setData(self.mastModel.index(0, 10), QVariant(self.floor_cmb.currentText()))
      
      rentStat = "Y" if self.rent_cb.checkState() == Qt.Checked else "N"
      self.mastModel.setData(self.mastModel.index(0, 11), QVariant(rentStat))
      
      self.mastModel.setData(self.mastModel.index(0, 12), QVariant(self.fitStart_de.date()))
      self.mastModel.setData(self.mastModel.index(0, 13), QVariant(self.fitEnd_de.date()))
      
      if self.scOwner_rb.isChecked():
          scto = "1"
      elif self.scTenant_rb.isChecked():
          scto = "2"
      else:
          scto = "3"
      self.mastModel.setData(self.mastModel.index(0, 14), QVariant(scto))
      
      if self.utilOwner_rb.isChecked():
          utilto = "1"
      elif self.utilTenant_rb.isChecked():
          utilto = "2"
      else:
          utilto = "3"
      self.mastModel.setData(self.mastModel.index(0, 15), QVariant(utilto))
      
      self.mastModel.setData(self.mastModel.index(0, 16), QVariant(self.idO_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 17), QVariant(self.statJoin_cmb.currentText().left(1)))
      self.mastModel.setData(self.mastModel.index(0, 18), QVariant(self.note_le.text()))
      self.mastModel.setData(self.mastModel.index(0, 19), QVariant(self.id_le.text()))
#      self.mastModel.setData(self.mastModel.index(0, 20), QVariant(self.joinTo.text()))
      self.mastModel.setData(self.mastModel.index(0, 21), QVariant(self.idT_le.text()))
# ga dipake      self.mastModel.setData(self.mastModel.index(0, 22), QVariant(self.cat_cmb.text()))
      self.mastModel.setData(self.mastModel.index(0, 23), QVariant(self.desc_te.toHtml()))
      
      sellStat = "Y" if self.sold_cb.checkState() == Qt.Checked else "N"
      self.mastModel.setData(self.mastModel.index(0, 24), QVariant(sellStat))
      self.mastModel.setData(self.mastModel.index(0, 25), QVariant(self.sold_de.date()))
      elcStat = "Y" if self.elc_cb.checkState() == Qt.Checked else "N"
      self.mastModel.setData(self.mastModel.index(0, 26), QVariant(elcStat))
      wtrStat = "Y" if self.wtr_cb.checkState() == Qt.Checked else "N"
      self.mastModel.setData(self.mastModel.index(0, 27), QVariant(wtrStat))
      gasStat = "Y" if self.gas_cb.checkState() == Qt.Checked else "N"
      self.mastModel.setData(self.mastModel.index(0, 28), QVariant(gasStat))
      scStat = "Y" if self.sc_cb.checkState() == Qt.Checked else "N"
      self.mastModel.setData(self.mastModel.index(0, 29), QVariant(scStat))
      sfStat = "Y" if self.sf_cb.checkState() == Qt.Checked else "N"
      self.mastModel.setData(self.mastModel.index(0, 30), QVariant(sfStat))
      
      if not self.mastModel.submitAll():
          return
      if not QSqlDatabase.database().commit():
          return
      return True
      
            
  def initData(self):
      hari = self.util.getServerToday()
      if self.tipe != "add":
          query = QSqlQuery(self.db)          
          qStr = "select unit, kode_tu, nama_unit, luas_unit , bast, awal_sewa, akhir_sewa, kode_bu, tlp_unit, buka, floor, status_srd, awal_fitout, akhir_fitout, sc_bill_to, util_bill_to, owner, status_join, note , kode_unit, join_to, tenant, usaha, desc_unit , status_jual, tgl_jual, stat_bill_elc, stat_bill_air, stat_bill_gas, stat_bill_sc, stat_bill_sf from base_unit where kode_unit = '"+self.tipe+"'"
          
          query.exec_(qStr)
          query.next()
          self.unit_le.setText(unicode(query.value(0).toString()))
          
          brs = self.tipeModel.match(self.tipeModel.index(0, 0), 0, query.value(1),1, Qt.MatchWrap )
          if len(brs) > 0:
              self.tipe_cmb.setCurrentIndex(brs[0].row())
          
          self.name_le.setText(unicode(query.value(2).toString()))
          self.sqrm_le.setText(unicode(query.value(3).toString()))
          self.ho_de.setDate(query.value(4).toDate())
          self.rentStart_de.setDate(query.value(5).toDate())
          self.rentEnd_de.setDate(query.value(6).toDate())
          
          brs = self.bisnisModel.match(self.bisnisModel.index(0, 0), 0, query.value(7),1, Qt.MatchWrap )
          if len(brs) > 0:
              self.cat_cmb.setCurrentIndex(brs[0].row())
          
          self.phone_le.setText(unicode(query.value(8).toString()))          
          self.open_cb.setCheckState(Qt.Checked if query.value(9).toString() == "1" else Qt.Unchecked)
          self.floor_cmb.setCurrentIndex(self.floor_cmb.findText(query.value(10).toString(),  Qt.MatchExactly))
          self.rent_cb.setCheckState(Qt.Checked if query.value(11).toString() == "Y" else Qt.Unchecked)
          self.fitStart_de.setDate(query.value(12).toDate())
          self.fitEnd_de.setDate(query.value(13).toDate())
          
          scto = query.value(14).toString()
          if scto == "1":
              self.scOwner_rb.setChecked(True)
          elif scto == "2":
              self.scTenant_rb.setChecked(True)
          else:
              self.scDev_rb.setChecked(True)
              
          utilto = query.value(15).toString()
          if utilto == "1":
              self.utilOwner_rb.setChecked(True)
          elif utilto == "2":
              self.utilTenant_rb.setChecked(True)
          else:
              self.utilDev_rb.setChecked(True)
          
          join = self.dataJoin[unicode(query.value(17).toString())]
          self.statJoin_cmb.setCurrentIndex(self.statJoin_cmb.findText(join, Qt.MatchExactly))
          
          self.note_le.setText(unicode(query.value(18).toString()))
          self.id_le.setText(unicode(query.value(19).toString()))
          joinTo_kode = query.value(20).toString()
#          self.id_le.setText(unicode(query.value(22).toString()))
          self.desc_te.setHtml(query.value(23).toString())
          self.sold_cb.setCheckState(Qt.Checked if query.value(24).toString() == "Y" else Qt.Unchecked)
          self.sold_de.setDate(query.value(25).toDate())          
          self.elc_cb.setCheckState(Qt.Checked if query.value(26).toString() == "Y" else Qt.Unchecked)
          self.wtr_cb.setCheckState(Qt.Checked if query.value(27).toString() == "Y" else Qt.Unchecked)
          self.gas_cb.setCheckState(Qt.Checked if query.value(28).toString() == "Y" else Qt.Unchecked)
          self.sc_cb.setCheckState(Qt.Checked if query.value(29).toString() == "Y" else Qt.Unchecked)
          self.sf_cb.setCheckState(Qt.Checked if query.value(30).toString() == "Y" else Qt.Unchecked)
          
          self.idT_le.setText(unicode(query.value(21).toString()))
          self.idO_le.setText(unicode(query.value(16).toString()))
          qStr = "select nama_pemilik_penyewa, concat(alamat_pemilik_penyewa,' ',kota_pemilik_penyewa,' ',kode_pos), no_telp, no_fax, no_ponsel, nama_pt, concat(alamat_pt,' ',kota_pt), no_telp_pt, no_fax_pt, email, kode_tt, id_no, npwp from master_pemilik_penyewa where kode_pemilik_penyewa = '"+self.idO_le.text()+"'"
          query.exec_(qStr)
          while query.next():          
              self.nameO_le.setText(query.value(0).toString())
              self.addrO_le.setText(query.value(1).toString())
              self.typeO_le.setText(query.value(10).toString())
              self.phoneO_le.setText(query.value(2).toString())
              self.faxO_le.setText(query.value(3).toString())
              self.hpO_le.setText(query.value(4).toString())
              self.compO_le.setText(query.value(5).toString())
              self.addr2O_le.setText(query.value(6).toString())
              self.phone2O_le.setText(query.value(7).toString())
          
          qStr = "select nama_pemilik_penyewa, concat(alamat_pemilik_penyewa,' ',kota_pemilik_penyewa,' ',kode_pos), no_telp, no_fax, no_ponsel, nama_pt, concat(alamat_pt,' ',kota_pt), no_telp_pt, no_fax_pt, email, kode_tt, id_no, npwp from master_pemilik_penyewa where kode_pemilik_penyewa = '"+self.idT_le.text()+"'"
          query.exec_(qStr)
          while query.next():
              self.nameT_le.setText(query.value(0).toString())
              self.addrT_le.setText(query.value(1).toString())
              self.typeT_le.setText(query.value(10).toString())
              self.phoneT_le.setText(query.value(2).toString())
              self.faxT_le.setText(query.value(3).toString())
              self.hpT_le.setText(query.value(4).toString())
              self.compT_le.setText(query.value(5).toString())
              self.addr2T_le.setText(query.value(6).toString())
              self.phone2T_le.setText(query.value(7).toString())
          
          qStr = "select unit from base_unit where kode_unit = '"+joinTo_kode+"'"
          query.exec_(qStr)
          while query.next():
              self.joinTo_le.setText(query.value(0).toString())
      self.initFinished = True

  def idBaru(self):
      kode = "UNIT"
      per = self.util.getServerToday().date().toString("MMyyyy")
      noAkhir = self.util.getNewId(kode, per, "Base Unit")
      id = "0"*(12 - len(str(noAkhir)))+str(noAkhir)
      return id
            
  def hitungTotal(self):
      totBrs = self.billModel.rowCount()
      jum = 0
#      for i in range(totBrs):
#          record = self.detModel.record(i)
#          jum += record.value(2).toDouble()[0]
      
  def validasi(self):
      valid = True
      for lineEdit in self.lineedits:
           if lineEdit.text().isEmpty():
               QMessageBox.warning(self, "Unit","Data not valid / Empty column.")
               return False
      
      if self.joinEdited:
          jum_brs = self.joinModel.rowCount()
          query = QSqlQuery()
          for i in range(jum_brs):
              toko = self.joinModel.record(i).value(2).toString()
              query.exec_("select kode_unit from base_unit where unit = '"+toko+"'")
              if query.next():
                  self.joinModel.setData(self.joinModel.index(i, 3), query.value(0))
              else:
                  self.tab_det.setCurrentIndex(2)
                  QMessageBox.warning(self, "Unit Edit", "Unit not found. Please check join unit.")
                  return False
      
      return valid
            
  def detail_bill(self,  jns,  data): 
      self.tab_det.setCurrentIndex(4)
      jum_brs = self.billModel.rowCount()
      if jum_brs > 0:
          brs = self.billModel.match(self.billModel.index(0, 2), 2, QVariant(jns),-1, Qt.MatchWrap )
          if len(brs) == 0:
              jum_brs = 0
          else:
              for i in range(len(brs)):
                  self.billModel.setData(self.billModel.index(brs[i].row(), 6), QVariant(data))
      else:
          jum_brs = 0
          
          
      if jum_brs == 0:
          if data == "Y" and jns != "LMP":
              self.urutBill += 1
              QSqlDatabase.database().transaction()
              row = self.billModel.rowCount()      
              self.billModel.insertRow(row)
              self.billModel.setData(self.billModel.index(row, 0), QVariant(self.id_le.text()))
              self.billModel.setData(self.billModel.index(row, 1), QVariant(self.urutBill))
              self.billModel.setData(self.billModel.index(row, 2), QVariant(jns))
              self.billModel.setData(self.billModel.index(row, 6), QVariant("Y"))
              QSqlDatabase.database().commit()
              if jns == "SC" or jns == "SF":
                  self.setTagih("sfsc",  row)
              else:
                  self.setTagih("util",  row)
              index = self.billModel.index(row, 3)
              self.billing_tbv.setCurrentIndex(index)
              self.billing_tbv.edit(index)
              
              
  def setTagih(self,  jns,  brs): 
      tagih = "3"
      if jns == "util":
          if self.utilOwner_rb.isChecked():
              tagih = "1"
          elif self.utilTenant_rb.isChecked():
              tagih = "2"
      else:
          if self.scOwner_rb.isChecked():
              tagih = "1"
          elif self.scTenant_rb.isChecked():
              tagih = "2"
          
      if tagih == "1":
          tagih = self.idO_le.text()
      elif tagih == "2":
          tagih = self.idT_le.text()
      else:
          tagih = "CBP100001"
          
      self.billModel.setData(self.billModel.index(brs, 5), QVariant(tagih))
          
          
  def setTagihAll(self,  jns,  tagih): 
      jum_brs = self.billModel.rowCount()
      for i in range(jum_brs):
          tipe = self.billModel.record(i).value(2).toString()
          if jns == "sfsc":
              if tipe == "SC" or tipe == "SF":
                  self.billModel.setData(self.billModel.index(i, 5), QVariant(tagih))
                  print tipe
          else:
              if tipe != "SC" and tipe != "SF":
                  self.billModel.setData(self.billModel.index(i, 5), QVariant(tagih))
                  
class DetailDelegate(QSqlRelationalDelegate):
    def __init__(self, parent=None):
        super(DetailDelegate, self).__init__(parent)
        self.tipe = QStringList()
        listTipe = ["SC",  "SF",  "ELC",  "WTR",  "GAS",  "LMP"]
        for  i in range(len(listTipe)):
            self.tipe.append(listTipe[i])
        
    def paint(self, painter, option, index):
        myoption = QStyleOptionViewItem(option)
        if index.column() == 2:
            myoption.displayAlignment |= Qt.AlignRight|Qt.AlignVCenter
        QSqlRelationalDelegate.paint(self, painter, myoption, index)
            
    def createEditor(self, parent, option, index):
        if index.column() == 2:
            combobox = QComboBox(parent)
            combobox.addItems(self.tipe)
            return combobox
        elif index.column() == 6:
            cb = QCheckBox(parent)
            return cb
        else:
            return QSqlRelationalDelegate.createEditor(self, parent, option, index)
            
    def setEditorData(self, editor, index):
        teks = index.model().data(index, Qt.DisplayRole).toString()
        if  index.column() == 2:
            editor.setCurrentIndex(editor.findText(teks, Qt.MatchExactly))
        elif index.column() == 6:
            editor.setCheckState(Qt.Checked if teks == "Y" else Qt.Unchecked)
        else:
            QSqlRelationalDelegate.setEditorData(self, editor, index)
            
    def setModelData(self, editor, model, index):
        if index.column() == 2:
            model.setData(index, QVariant(editor.currentText()))
        elif index.column() == 6:
            model.setData(index, QVariant("Y" if editor.checkState() == Qt.Checked else "N"))
        else:
            QSqlRelationalDelegate.setModelData(self, editor, model, index)
            
            
if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = UnitEdit()
    form.show()
    app.exec_()
